<?php

$columns = array();
foreach ($this->grid->getHeaders() as $header) {
    if ($header->type === Core_Grid::TYPE_DATA) {
        $columns[$header->id] = $header->name;
    }
}
?>
<div class="filter-wrapper">
    <span class="grid-buttons"><?php echo $this->placeholder('grid_buttons') ?></span>
    <span class="grid-filter">
        <?php if ($this->showFilter): ?>
            <?php echo $this->formSelect('filter-column', null, null, $columns) ?>
            <input type="text" id="filter-value" />
            <a href="#" id="filter-button" class="button"><?php echo $this->__('Ok')?></a>
            <a href="#" id="filter-reset" class="button"><?php echo $this->__('Reset')?></a>
           <?php endif; ?>
    </span>
</div>
<div id="grid" data-url="<?php echo $this->url(array('action' => 'grid'), 'default') ?>"></div>
<script>
$(function() {
    $('#grid').grid().delegate('a.delete', 'click', function() {
        if (confirm('Are you sure you want to delete this?')) {
            $.post(this.href, function(res) {
                $('#grid').data('plugin_grid').refresh();
            });
        }
        return false;
    });

    $('#filter-button').click(function() {
        var filterColumn = $('#filter-column').val()
          , filterValue = $('#filter-value').val();
        $('#grid').data('plugin_grid').filter(filterColumn, filterValue);
        return false;
    });

    $('#filter-reset').click(function() {
        $('#filter-value').val('');
        $('#grid').data('plugin_grid').reset();
        return false;
    });

    $('#grid').delegate('#selectAllCheckbox', 'click', (function() {
        this.checked ? $('#grid').find(':checkbox').attr('checked', 'checked')
                     : $('#grid').find(':checkbox').removeAttr('checked');
    }));

    $('#delete-all-button').click(function() {
        var url = this.href
          , res = [];
        if (confirm('Are you sure you want to delete this?')) {
            $('#grid').find("input:checked").each(function() {
                res.push(this.value);
            });
            if(!res.length) {
                alert('No row selected');
            } else {
                $.post(url, { ids: res }, function() {
                    $('#grid').data('plugin_grid').refresh();
                });
            }
        }
        return false;
    });
});
</script>